package tool

import (
	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/audio"
	"github.com/hajimehoshi/ebiten/v2/audio/vorbis"
	"github.com/hajimehoshi/ebiten/v2/ebitenutil"
	"log"
	"os"
)

func ReadFileToImg(path string) *ebiten.Image {

	img, _, err := ebitenutil.NewImageFromFile("assets/img/" + path)
	if err != nil {
		log.Fatal("加载图片失败:", err)
	}
	playerImg := ebiten.NewImageFromImage(img)
	return playerImg
}

func ReadFileOgg(ctx *audio.Context, path string) *audio.Player {
	f, err := os.Open("assets/audio/" + path)
	if err != nil {
		log.Fatal("打开音效文件失败:", err)
	}
	stream, err := vorbis.DecodeWithoutResampling(f)
	if err != nil {
		log.Fatal("解析 OGG 音频失败:", err)
	}
	player, err := ctx.NewPlayer(stream)
	if err != nil {
		log.Fatal("创建播放器失败:", err)
	}
	return player
}

func ReadBGM(ctx *audio.Context, path string) *audio.Player {
	f, err := os.Open("assets/audio/" + path)
	if err != nil {
		log.Fatal("打开音效文件失败:", err)
	}
	stream, err := vorbis.DecodeWithoutResampling(f)
	if err != nil {
		log.Fatal("解析 BGM 音频失败:", err)
	}
	loop := audio.NewInfiniteLoop(stream, stream.Length())
	player, err := ctx.NewPlayer(loop)
	if err != nil {
		log.Fatal("创建播放器失败:", err)
	}
	return player
}

func ReadShader(path string) *ebiten.Shader {
	shaderSrc, err := os.ReadFile("assets/shader/" + path)
	if err != nil {
		log.Fatal("读取 shader 文件失败:", err)
	}

	shader, err := ebiten.NewShader(shaderSrc)
	if err != nil {
		log.Fatal("创建 shader 失败:", err)
	}
	return shader
}
